<template>
  <div>
    <!-- 工单编号行 -->
    <div class="search">
      <el-form :inline="true" :model="params" class="demo-form-inline">
        <el-form-item label="点位搜索:">
          <el-input v-model="params.name" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="区域搜索:">
          <el-select v-model="params.regionId" clearable placeholder="请输入">
            <el-option
              v-for="item in Workorder"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit(params.regionId)">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 主体内容  新建 -->
    <div class="result">
      <div class="operation">
        <el-row>
          <el-button
            size="medium"
            icon="el-icon-circle-plus-outline"
            class="one"
            @click="addbuild"
          >新建</el-button>
        </el-row>
      </div>
      <!-- 表格数据 -->
      <div>
        <template>
          <el-table
            :data="PointPosition"
            style="width: 100%"
            :row-style="{ height: '44px' }"
            :cell-style="{ padding: '3px' }"
          >
            <el-table-column
              label="序号"
              type="index"
              :index="indexMethod"
              width="80"
            />
            <el-table-column prop="name" label="点位名称" width="171" />
            <el-table-column prop="region.name" label="所在区域" width="169" />
            <el-table-column
              prop="businessType.name"
              label="商圈类型"
              width="169"
            />
            <el-table-column prop="ownerName" label="合作商" width="169" />
            <!-- :show-overflow-tooltip="true" -->
            <el-table-column
              prop="addr"
              label="详细地址"
              width="169"
            />
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  class="detail"
                  @click="handleClick(scope.row)"
                >查看详情</el-button>
                <el-button
                  type="text"
                  class="detail"
                  @click="modify(scope.row)"
                >修改</el-button>
                <el-button
                  type="text"
                  class="piramy"
                  @click="del(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </div>
    <!-- 分页 -->
    <el-row type="flex" justify="center" align="middle" style="height: 60px">
      <el-col class="pstion">
        共{{ totalCount }}条记录
        第{{ params.pageIndex }}/{{ totalPage }}页
      </el-col>
      <el-pagination
        :page-size="params.pageSize"
        :total="totalCount"
        :current-page="params.pageIndex"
        layout="prev,next"
        prev-text="上一页"
        next-text="下一页"
        @current-change="currentChangeFn"
      />
    </el-row>
    <!-- 新建 dialog -->
    <el-dialog
      :title="title"
      :visible="dialogVisible"
      width="630px"
      @close="close"
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="140px" class="demo-ruleForm">
        <el-form-item label="点位名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            maxlength="15"
          />
        </el-form-item>
        <el-form-item label="所在区域" prop="regionId">
          <el-select v-model="ruleForm.regionId" placeholder="请选择" style="width:90%">
            <el-option
              v-for="item in Workorder"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属商圈" prop="businessId">
          <el-select v-model="ruleForm.businessId" placeholder="请选择" style="width:90%">
            <el-option
              v-for="item in BusinessList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商" prop="ownerId">
          <el-select v-model="ruleForm.ownerId" placeholder="请选择" style="width:90%">
            <el-option
              v-for="item in cooperation"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- prop="addrrr" -->
        <el-form-item label="详细地址" prop="ownerId">
          <el-cascader
            v-model="selectedOptions"
            size="large"
            :options="options"
            style="width:90%"
            @change="handleChange"
          />

        </el-form-item>
        <el-form-item prop="detailedAddresstwo">
          <el-input
            v-model="detailedAddresstwo"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
            maxlength="60"
            show-word-limit
            style="width:90%"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog
      title="点位详情"
      :visible="see"
      width="630px"
      @close="see = false"
    >
      <template>
        <el-table
          :data="seeDetails"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            :index="indexMethod"
            label="序号"
            width="80"
          />
          <el-table-column
            prop="innerCode"
            label="机器编号"
            width="158"
          />
          <el-table-column
            prop="vmStatus"
            label="设备详情"
            width="158"
          />
          <el-table-column
            prop="lastSupplyTime"
            label="最后一次供货时间"
            width="158"
          />
        </el-table>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 商圈列表  合作商
import { AreaList, AreaDetails, BusinessCircle, Partners, addPosition, getvmList, modifyPosition, delPosition } from '@/api'
// 城市区3级联动
import { regionData, CodeToText } from 'element-china-area-data'
import dayjs from 'dayjs'
export default {
  data() {
    return {
      // 拼接城市名字
      ccc: '',
      // 备注 + 城市名
      detailedAddresstwo: '',
      // 查看详情
      see: false,
      seeDetails: [],
      // 城市区3级联动
      options: regionData,
      selectedOptions: [],
      // 表单校验数据等
      ruleForm: {
        name: '', // 点位名称
        addr: '', // 详细地址
        areaCode: 0, // 最后一级区域id
        createUserId: 1, // 创建人Id
        regionId: '', // 所属区域Id
        businessId: '', // 所属商圈Id
        ownerId: '', // 合作商Id
        ownerName: '' // 合作商名称
      },
      rules: {
        name: [
          { required: true, message: '请输入' }
        ],
        addr: [
          { required: true, message: '请输入' }
        ],
        regionId: [
          { required: true, message: '请输入' }
        ],
        businessId: [
          { required: true, message: '请输入' }
        ],
        ownerName: [
          { required: true, message: '请输入' }
        ],
        ownerId: [
          { required: true, message: '请输入' }
        ],
        selectedOptions: [
          { required: true, message: '请输入' }
        ],
        detailedAddress: [
          { required: true, message: '请输入' }
        ]
      },
      // 商圈列表
      BusinessList: [],
      // 合作商
      cooperation: [],
      // 序号 点位名称 列表总数据
      PointPosition: [],

      dialogVisible: false,

      // 区域搜索 列表
      Workorder: {},

      // 列表总数据
      totalCount: 1, // 总数量
      totalPage: 1, // 总页数
      params: {
        pageIndex: 1, // 当前页码
        pageSize: 10, // 每页条数
        name: '', // 查询点位 参数
        regionId: ''// 区域查询 参数
      },
      // 分辨新增 还是修改 变量
      isShow: false,
      // 修改接口 所需 id 点击修改 在每行数据中得到
      correctId: ''
    }
  },
  computed: {
    title() {
      return this.isShow ? '修改点位' : '新增点位'
    }
  },
  async created() {
    // 列表总数据
    this.getAreaDetails()
    // 区域 列表
    this.getAreaList()
  },
  methods: {
    // 格式化时间
    formateTime(value) {
      return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    },
    // 城市区3级联动
    handleChange(val) {
      // console.log(val)
      var loc = ''
      for (let i = 0; i < this.selectedOptions.length; i++) {
        loc += CodeToText[this.selectedOptions[i]]
      }
      //  拼接  选中城市名字
      const city = [CodeToText[val[0]], CodeToText[val[1]], CodeToText[val[2]]]
      this.ccc = city.join('-') + '-' + this.detailedAddresstwo
      console.log(loc)
      // this.ruleForm.addr = loc
      // 最后一级区域id
      this.ruleForm.areaCode = this.selectedOptions[2]
    },
    // 点击新建调用接口
    async addbuild(val) {
      // console.log(CodeToText)
      this.dialogVisible = true
      this.getAreaList() // 区域

      const res = await BusinessCircle()// 合作商
      // console.log(res)
      this.BusinessList = res

      const { currentPageRecords } = await Partners(this.params)// 结构 合作商数据
      this.cooperation = currentPageRecords
    },
    // 新建提交
    submit() {
      // this.dialogVisible = false
      // 兜底校验
      this.$refs.ruleForm.validate(async(valid) => {
        if (!valid) return
        // 根据 id 找到 对应ownerId 的合作商名字
        const titycc = this.cooperation.find(item => item.id === this.ruleForm.ownerId)
        this.ruleForm.ownerName = titycc.name
        // 拼接选中城市 和 描述 在赋值给请求所需携带参数
        this.ruleForm.addr = this.ccc + this.detailedAddresstwo
        if (this.isShow) {
          await modifyPosition(this.ruleForm, this.correctId)
        } else {
          await addPosition(this.ruleForm)
        }
        this.$message.success(this.title + '成功')
        // console.log(res)
        // 渲染页面
        this.getAreaDetails()
        // 关闭弹窗
        this.close()
      })
    },
    // 关闭新建弹窗
    close() {
      // 清空
      this.dialogVisible = false
      this.$refs.ruleForm.resetFields()
      this.detailedAddresstwo = ''
      this.selectedOptions = []
      this.ruleForm = {
        name: '',
        addr: '',
        areaCode: '',
        createUserId: 1,
        regionId: '',
        businessId: '',
        ownerId: '',
        ownerName: ''
      }
      this.isShow = false
    },
    // 封装 列表总数据
    async getAreaDetails() {
      const res = await AreaDetails(this.params)
      // console.log(res)
      this.PointPosition = res.currentPageRecords
      // 总条数
      this.totalCount = Number(res.totalCount)
      // 总页数
      this.totalPage = res.totalPage
    },
    // 封装 区域总数据
    async getAreaList() {
      const res = await AreaList(this.params)
      // console.log(res)
      this.Workorder = res.currentPageRecords
      // console.log(this.Workorder)
    },
    // 查询 点位搜索 区域搜索
    onSubmit(val) {
      // console.log(val)
      this.getAreaDetails()
    },
    // 查看详情
    async handleClick(val) {
      // console.log(val)
      this.see = true
      this.seeDetails = await getvmList(val.id)
      // 设备状态  0 1 3 判断
      this.seeDetails.forEach(item => {
        if (item.vmStatus === 0) {
          item.vmStatus = '未投放'
        }
        if (item.vmStatus === 1) {
          item.vmStatus = '运营'
        }
        if (item.vmStatus === 3) {
          item.vmStatus = '撤机'
        }

        // 时间格式化
        item.lastSupplyTime = dayjs(item.lastSupplyTime).format(
          'YYYY.MM.DD HH:mm:ss'
        )
      })
    },
    // 修改
    async modify(val) {
      this.isShow = true
      this.dialogVisible = true
      // 获取 修改 所需id
      this.correctId = val.id

      // 点击时获取最新数据
      // this.getAreaDetails()
      // this.getAreaList()

      this.ruleForm = val

      // 处理城市区 回显问题
      // 拿到最后一级区 id 匹配所有城市
      // 取出所有城市 数key 和 value 值,  map生成数组 , return对象放进数据中
      const cheng = Object.keys(CodeToText)
      const cityName = Object.values(CodeToText)
      const city = cheng.map((item, index) => {
        return {
          code: item,
          cName: cityName[index]
        }
      })
      // console.log(city)
      // 选中城市 切割成数组 做匹配id对应城市赋值
      const arr2 = val.addr.split('-')
      // console.log(arr2)
      const one = city.find(item => item.cName === arr2[0])
      const two = city.find(item => item.cName === arr2[1])
      const three = city.find(item => item.cName === arr2[2])
      // console.log(one.code, two.code, three.code)
      const region = []
      region.push(one.code, two.code, three.code)
      // console.log(region)
      this.selectedOptions = region
      // 处理备注回显问题
      this.detailedAddresstwo = arr2[arr2.length - 1]

      this.ruleForm.ownerId = val.ownerId
      this.ruleForm.businessId = val.businessId
    },
    // 序号
    indexMethod(index) {
      return index + 1
    },
    // 翻页
    currentChangeFn(val) {
      this.params.pageIndex = val
      this.getAreaDetails()
    },
    // 删除
    del(val) {
      // console.log(val)
      // 友好提示
      this.$confirm('确定删除该点位么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 调用接口
        await delPosition(val.id)
        // 成功提示
        this.$message.success('删除点位成功')
        // 刷新页面
        this.getAreaDetails()
      }).catch(() => {
        // 成功提示
        this.$message.error('点位下有售货机，不可删除')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
// 头部固定
.search {
  display: flex;
  display: -webkit-box;
  background: #fff;
  height: 64px;
  -webkit-box-align: center;
  align-items: center;
  margin-bottom: 20px;
  padding-left: 17px;
  background-color: #fff;
}
.demo-form-inline {
  height: 36px;
}
// 新建
.result {
  padding: 20px 15px 19px 17px;
  background-color: #fff;
  .operation {
    margin-bottom: 20px;
    .one {
      background: linear-gradient(135deg,#ff9743,#ff5e20)!important;
      color: #fff;
    }
    .two{
          background-color: #fbf4f0!important;
    }
  }
}
.el-input{
  width: 90%;
}
</style>
